// import type { Position } from '@turf/turf'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import type { AssetHomeMarkerData, AssetHomeMapPropsType, AssetHomeMapStateType } from './typings'
import { defineComponent, ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue'
import { useStore } from 'vuex'
import {
  keys as Keys
  // values as Values
} from 'lodash'
// import { lineString, bbox, randomPoint, polygon, booleanPointInPolygon } from '@turf/turf'
import { ElLoading, ElMessage } from 'element-plus'
import useAMap from '~/hooks/useAMap'
import lampost from '~/assets/lightPoleOn.png'
// import circlesvg from '~/assets/circle.svg'
// import styles from '../index.module.scss'

export default defineComponent({
  name: 'AssetHomeMap',
  props: [
    'id',
    'initCallback',
    'patternData',
    'activeModules',
    'patternMarkerType',
    'getMapZoom',
    'activeOptionsBar'
  ],
  emits: [
    'changePatterMarkerInfoView',
    'changePatterMarkerInfoPosition',
    'changeLoopInfoView',
    'changePatterPolylineInfoView',
    'getMarkerInfo'
  ],
  setup(props: AssetHomeMapPropsType, { emit, expose }) {
    const store = useStore()
    const loadRef = ref<LoadingInstance>()
    const mapDomRef = ref()
    const state = reactive<AssetHomeMapStateType>({
      mapCenter: [],
      polygon: {},
      areaCenterMarker: {},
      patternMarker: {},
      patternPolyline: {},
      activePatternPolylineId: {},
      lamppostMarker: {},
      lampMarker: {},
      lampTitleMarker: {},
      distributionMarker: {}
    })
    const lamppost = shallowRef()
    const lamp = shallowRef()
    const lamptitle = shallowRef()
    const distribution = shallowRef()
    const satellite = shallowRef()
    const [mapRef, aMapRef, amapIconRef] = useAMap(
      props.id,
      {
        zoom: 5
        // showIndoorMap: false,
        // showLabel: true
      },
      initAMap
    )

    // 随机获取地图面中包含的点
    // const handleGetMapRandomPoint = (
    //   lineStringData: number[],
    //   onePolygonData: number[]
    // ): [number, number] => {
    //   const turfLineString = lineString(lineStringData as unknown as Position[])
    //   const turfBbox = bbox(turfLineString)
    //   const turfPolygon = polygon(onePolygonData as unknown as Position[][])
    //   let turfRandomPoint = randomPoint(1, { bbox: turfBbox })
    //   while (!booleanPointInPolygon(turfRandomPoint.features[0], turfPolygon)) {
    //     turfRandomPoint = randomPoint(1, { bbox: turfBbox })
    //   }
    //   return turfRandomPoint.features[0].geometry.coordinates as [number, number]
    // }

    // 根据父组建请求接口返回的生成地图图标配置
    const handleGenerateMarkerIcon = (optionsBar: AssetHomeMapPropsType['optionsBar']) => {
      state.loopOptions = {}
      state.markerIconOptions = optionsBar?.reduce(
        (markerIconOptions: AssetHomeMapStateType['markerIconOptions'], item) => {
          const { patternData } = props
          if (!patternData) return markerIconOptions
          // 是回路时跳过回路遍历
          if (item.code === 'DistributionLoop') {
            state.loopOptions![item.id] = {
              key: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.[0]?.select,
              legend: patternData![item.id].modelConfigDataVO?.base?.legend,
              zooms: patternData![item.id].modelConfigDataVO?.base?.maxScale
                ? [
                    patternData![item.id].modelConfigDataVO?.base?.minScale,
                    Math.floor(patternData![item.id].modelConfigDataVO?.base?.maxScale) + 0.9
                  ]
                : [],
              settings: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.reduce(
                (markerItemOption: Record<string, Record<string, any>>, childItem) => {
                  markerItemOption[childItem.value] = {
                    color: childItem.color,
                    lineColor: childItem.lineColor,
                    lineWidth: childItem.lineWidth,
                    lineOpacity: childItem.lineOpacity,
                    selectLineColor:
                      patternData![item.id].modelConfigDataVO?.select?.selectLineColor,
                    selectLineWidth:
                      patternData![item.id].modelConfigDataVO?.select?.selectLineWidth
                  }
                  return markerItemOption
                },
                {}
              )
            }
            return markerIconOptions
          }
          // 记录下灯杆的moduleId在绘制灯的时候需要用到
          if (item.code === 'LampPost') state.lampPostModuleId = item.id
          markerIconOptions![item.id] = {
            key: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.[0]?.select,
            isTag: patternData![item.id].modelConfigDataVO?.base?.isTag,
            tagName: patternData![item.id].modelConfigDataVO?.base?.tagName,
            legend: patternData![item.id].modelConfigDataVO?.base?.legend,
            infoVisible: patternData![item.id].modelConfigDataVO?.info?.infoVisible,
            zooms: patternData![item.id].modelConfigDataVO?.base?.maxScale
              ? [
                  patternData![item.id].modelConfigDataVO?.base?.minScale,
                  Math.floor(patternData![item.id].modelConfigDataVO?.base?.maxScale) + 0.9
                ]
              : [],
            icons: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.reduce(
              (markerItemOption: Record<string, Record<string, any>>, childItem) => {
                markerItemOption[childItem.value] = {
                  width: childItem.iconWidth,
                  height: childItem.iconLength,
                  iconUrl: childItem.iconImageBase,
                  iconSize: [childItem.iconWidth, childItem.iconLength],
                  offset: [0, -childItem.iconLength],
                  bigVisible: patternData![item.id].modelConfigDataVO?.select?.selectVisible,
                  bigWidth: patternData![item.id].modelConfigDataVO?.select?.selectIconWidth,
                  bigHeight: patternData![item.id].modelConfigDataVO?.select?.selectIconLength,
                  bigIconSize: [
                    patternData![item.id].modelConfigDataVO?.select?.selectIconWidth,
                    patternData![item.id].modelConfigDataVO?.select?.selectIconLength
                  ],
                  bigOffset: [
                    0,
                    -patternData![item.id].modelConfigDataVO?.select?.selectIconLength +
                      childItem.iconLength
                  ]
                }
                return markerItemOption
              },
              {}
            )
          }
          return markerIconOptions
        },
        {}
      )
    }

    // 恢复地图默认中心点
    const handleRestMapCenter = () => {
      mapRef.value.setCenter(state.mapCenter)
    }

    // 设置地图信息
    const handleSetMapInfo = (mapData: Record<string, any>) => {
      if (mapRef.value && mapData) {
        state.mapCenter = [mapData.lon, mapData.lat]
        // 设置地图中心点和地图层级
        mapRef.value.setZoomAndCenter(mapData.layerLevel, state.mapCenter, false, 0)

        props.getMapZoom?.()
      }
    }

    // 清除地图绑定详情弹框事件
    const handleClearActiveMarkerEvent = () => {
      state.activeMarker = undefined
      // 如果当前的图标有放大的话 则清除放大状态
      // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
      const activeMarkerExtData = state.activePatternMarker?.getExtData?.()
      const activeMarker =
        state.patternMarker?.[activeMarkerExtData?.moduleId]?.[activeMarkerExtData?.id]
      if (state.activePatternMarker && activeMarker && activeMarkerExtData?.active) {
        activeMarker?.setExtData({ ...(activeMarker?.getExtData() || []), active: true })
        handleChangeEnlargeMarker({ target: activeMarker })
      }

      // if (state.activePatternMarker)
      //   handleChangeEnlargeMarker({ target: state.activePatternMarker })
      state.activePatternMarker = undefined
      // emit('changeAreaInfoView', 0, 0, undefined, undefined)
      emit('changePatterMarkerInfoView')
      mapRef.value.clearEvents('mapmove')
      mapRef.value.clearEvents('resize')
      // mapRef.value.clearEvents('moveend')
      // 继续为地图绑定拖拽结束事件  结束后要去触发请求 查询当前显示区域内的所有选中的值
      // mapRef.value.on('moveend', handleSearchMapMarkerByModuleId)
    }

    /**
     * 切换某个工区的展示和隐藏
     * 同时切换工区点和工区面 并将地图定位到当前选中的工区和最大层级
     * @param id 工区id
     * @param visible 展示/隐藏  (暂时废弃)
     */
    const handleChangePolygonVisible = async (id: string, visible: boolean) => {
      if (id && state.polygon[id]) {
        const { patternData } = props
        const araeData = state.polygon[id].getExtData()
        if (visible) {
          const selectData = patternData![araeData.moduleId].modelConfigDataVO?.select
          await mapRef.value.setZoomAndCenter(
            araeData?.minZoom ?? mapRef.value.getZoom(),
            state.areaCenterMarker[id]?.getPosition(),
            false,
            0
          )

          // 设置选中面边框加粗
          state.polygon[id].setOptions({
            strokeWeight: selectData.selectLineWidth
          })
          // state.polygon[id].show()
          // state.areaCenterMarker[id].show()
          handleSearchMapMarkerByModuleId()
          return
        } else {
          // 还原选中面
          state.polygon[id].setOptions({
            strokeWeight: araeData.width ?? 1
          })
        }
        // 如果有当前的点击的坐标点 则清除
        if (state.activeMarker?.getExtData?.()?.id === id) handleClearActiveMarkerEvent()
        // state.polygon[id].hide()
        // state.areaCenterMarker[id].hide()
      }
    }

    // 根据传入的工区id数组展示对应id的工区面其他的则隐藏
    const handleShowAreaPolygonByAreaId = (ids: string[]) => {
      Keys(state.polygon)?.forEach((key: string) => {
        if (ids?.includes(key)) {
          state.polygon[key]?.show()
          state.areaCenterMarker[key]?.show()
        } else {
          state.polygon[key]?.hide()
          state.areaCenterMarker[key]?.hide()
        }
      })
    }

    // 获取事件源中的坐标点并放大
    const handleChangeEnlargeMarker = (markerEvent: Record<string, any>) => {
      const extData = markerEvent.target.getExtData()
      extData.active = !extData.active
      const iconSetting =
        state.markerIconOptions![extData.moduleId]?.icons[
          extData?.[state.markerIconOptions![extData.moduleId].key as keyof AssetHomeMarkerData]
        ]
      if (!iconSetting.bigVisible) return
      const showMarker = state.patternMarker![extData.moduleId][extData.id]
      if (extData.active) {
        showMarker.setIcon({
          size: iconSetting.bigIconSize
        })
      } else {
        showMarker.setIcon({
          size: iconSetting.iconSize
        })
      }
      markerEvent.target.setExtData(extData)
    }

    // 根据传入类型判断选择什么接口请求详情数据
    const handleGetPatterMarkerInfoBy = async (extData: AssetHomeMarkerData) => {
      emit('getMarkerInfo', extData)
      let markerType = ''
      const result = await store.dispatch(
        'assetHome/GetAssetHomePopoverInfoDataByIdStationGisApi',
        {
          assetId: extData?.id,
          specialCode: 'basestation_home'
        }
      )
      // 当是配电设施时
      if (result?.data?.moduleCode === 'Distribution') {
        markerType = 'facility'
      } else if (result?.data?.moduleCode === 'LampPost') {
        // 当是灯杆时
        markerType = 'lightPole'
      } else if (result?.data?.moduleCode === 'LampBase') {
        // 当是灯时
        markerType = 'lamp'
      } else if (
        result?.data?.moduleCode === 'BaseStation' ||
        result?.data?.moduleCode === 'BaseBuild'
      ) {
        // 基站
        markerType = 'BaseStation'
      }
      if (result?.data?.assetId && markerType) {
        // 并查询是否有重叠点 如果有则一并返回
        if (extData.phase.type === 'point' && extData.phase.coordinates.length >= 2) {
          const res = await store.dispatch('assetHome/GetAssetHomeOverlapPointList', {
            lon: extData.phase.coordinates[0],
            lat: extData.phase.coordinates[1]
          })
          return {
            markerType,
            data: result?.data,
            pointList: res?.data || []
          }
        }

        return {
          markerType,
          data: result?.data
        }
      }
      return {
        markerType: undefined,
        data: undefined
      }
    }

    // 根据传入配电设施数据查询关联回路灯灯杆信息
    // const handleGetPatterPolylineInfoByDistributionId = async (extData: AssetHomeMarkerData) => {
    //   const result = await store.dispatch(
    //     'powerDistributionFacilities/GetAssociativeLoopInfoByDistributionId',
    //     {
    //       id: extData?.id
    //     }
    //   )
    //   return result?.data
    // }

    // 配电设施/灯杆/灯 地图拖拽时的回调
    const handleReplacePatterDomOffset = () => {
      const mapClientRect = mapDomRef.value.getBoundingClientRect()
      const patternMarkerOffset = mapRef.value.lngLatToContainer(
        state.activePatternMarker!.getPosition()
      )
      if (mapClientRect && patternMarkerOffset) {
        // 将获取到的 left top 和 工区数据发送给父组建
        emit(
          'changePatterMarkerInfoPosition',
          patternMarkerOffset.x + mapClientRect.left,
          patternMarkerOffset.y + mapClientRect.top - 2
        )
      }
    }

    // 配电设施/灯杆/灯 地图拖拽结束的回调
    const handleJudgeActivePatterMarkerInMap = async () => {
      if (!mapRef.value.getBounds().contains(state.activePatternMarker?.getPosition())) {
        emit('changePatterMarkerInfoView')
      } else if (!props.patternMarkerType) {
        const mapClientRect = mapDomRef.value.getBoundingClientRect()
        const patternMarkerOffset = mapRef.value.lngLatToContainer(
          state.activePatternMarker!.getPosition()
        )
        const { markerType, data, pointList } = await handleGetPatterMarkerInfoBy(
          state.activePatternMarker?.getExtData()
        )
        if (mapClientRect && patternMarkerOffset) {
          // 将获取到的 left top 和 工区数据发送给父组建
          emit(
            'changePatterMarkerInfoView',
            patternMarkerOffset.x + mapClientRect.left,
            patternMarkerOffset.y + mapClientRect.top - 2,
            markerType,
            data,
            pointList
          )
        }
      }
    }

    // 点击配电设施/灯杆/灯回调
    const handleClickPatterMarker = async (markerEvent: Record<string, any>) => {
      const extData = markerEvent.target.getExtData()
      // if (state.activePatternMarker?.getExtData?.()?.id !== extData?.id) {
      if (state.markerIconOptions![extData.moduleId]?.infoVisible === 0) return
      // 先清除所有事件 防治其他的弹框影响
      // handleClearActiveMarkerEvent()
      await handleSearchMapMarkerByModuleId()
      const mapClientRect = mapDomRef.value.getBoundingClientRect()
      const patternMarkerOffset = mapRef.value.lngLatToContainer(markerEvent.target!.getPosition())
      // 将获取到的 left top 和 工区数据发送给父组建
      const { markerType, data, pointList } = await handleGetPatterMarkerInfoBy(extData)

      if (!data) return
      state.activePatternMarker = markerEvent.target

      // handleChangeEnlargeMarker({ target: state.activePatternMarker })
      emit(
        'changePatterMarkerInfoView',
        patternMarkerOffset.x + mapClientRect.left,
        patternMarkerOffset.y + mapClientRect.top + 18,
        markerType,
        data,
        pointList
      )
      // 给map注册拖动事件 让popover 随着拖动移动
      mapRef.value.on('mapmove', handleReplacePatterDomOffset)
      mapRef.value.on('resize', handleReplacePatterDomOffset)
      mapRef.value.on('moveend', handleJudgeActivePatterMarkerInMap)
      return
      // }
      // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
      if (state?.activePatternMarker?.getExtData?.()?.active)
        handleChangeEnlargeMarker({ target: state.activePatternMarker })
      state.activePatternMarker = undefined
      handleClearActiveMarkerEvent()
      emit('changePatterMarkerInfoView')
    }

    // 每次拖拽结束后判断回路弹框是否在可视区域内  如果不在则关闭弹框
    // const handleJudgeActiveLoopInfoInMap = async () => {
    //   if (!mapRef.value.getBounds().contains(state.activePatternMarker?.getPosition())) {
    //     emit('changePatterPolylineInfoView')
    //   } else if (!props.patternMarkerType) {
    //     const mapClientRect = mapDomRef.value.getBoundingClientRect()
    //     const patternMarkerOffset = mapRef.value.lngLatToContainer(
    //       state.activePatternMarker!.getPosition()
    //     )
    //     const extData = state.activePatternMarker?.getExtData()
    //     const data = await handleGetPatterPolylineInfoByDistributionId(extData)
    //     if (mapClientRect && patternMarkerOffset) {
    //       // 将获取到的 left top 和 工区数据发送给父组建
    //       emit(
    //         'changePatterPolylineInfoView',
    //         patternMarkerOffset.x + mapClientRect.left,
    //         patternMarkerOffset.y + mapClientRect.top - 2,
    //         extData.name,
    //         data,
    //         state.activePatternPolylineId[extData.id]
    //       )
    //     }
    //   }
    // }

    // 点击配电设施右键回调
    // const handleRightClickPatterMarker = async (markerEvent: Record<string, any>) => {
    //   const extData = markerEvent.target.getExtData()
    //   if (state.activePatternMarker?.getExtData?.()?.id !== extData?.id) {
    //     if (state.markerIconOptions![extData.moduleId]?.infoVisible === 0) return
    //     // 先清除所有事件 防治其他的弹框影响
    //     handleClearActiveMarkerEvent()
    //     mapRef.value.setCenter(markerEvent.target!.getPosition(), false, 0)
    //     await handleSearchMapMarkerByModuleId()

    //     const mapClientRect = mapDomRef.value.getBoundingClientRect()
    //     const patternMarkerOffset = mapRef.value.lngLatToContainer(
    //       markerEvent.target!.getPosition()
    //     )

    //     const data = await handleGetPatterPolylineInfoByDistributionId(extData)
    //     if (!data) return
    //     state.activePatternMarker = markerEvent.target
    //     handleChangeEnlargeMarker({ target: state.activePatternMarker })
    //     // 如果当前配电设施下没有任何灯杆数据且为空时 创建一个空数组
    //     if (!state.activePatternPolylineId?.[extData?.id])
    //       state.activePatternPolylineId[extData.id] = []
    //     emit(
    //       'changePatterPolylineInfoView',
    //       patternMarkerOffset.x + mapClientRect.left,
    //       patternMarkerOffset.y + mapClientRect.top - 2,
    //       extData.name,
    //       data,
    //       state.activePatternPolylineId[extData.id]
    //     )
    //     // 给map注册拖动事件 让popover 随着拖动移动  拖动移动可与上面的共用
    //     mapRef.value.on('mapmove', handleReplacePatterDomOffset)
    //     mapRef.value.on('resize', handleReplacePatterDomOffset)
    //     mapRef.value.on('moveend', handleJudgeActiveLoopInfoInMap)
    //     return
    //   }
    //   // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
    //   if (state?.activePatternMarker?.getExtData?.()?.active)
    //     handleChangeEnlargeMarker({ target: state.activePatternMarker })
    //   state.activePatternMarker = undefined
    //   handleClearActiveMarkerEvent()
    //   emit('changePatterPolylineInfoView')
    // }

    // 根据传入的折线对象和选中状态来切换选中样式
    const handleChangePatternPolylineActiveStyle = (
      active: boolean,
      patternPolyline: Record<string, any>
    ) => {
      const extData = patternPolyline.getExtData()
      const loopKeyValue = state.loopOptions![extData.moduleId]?.key as keyof AssetHomeMarkerData
      patternPolyline.setOptions({
        strokeColor:
          state.loopOptions![extData.moduleId]?.settings[extData?.[loopKeyValue]]?.lineColor,
        strokeWeight: active
          ? state.loopOptions![extData.moduleId]?.settings[extData?.[loopKeyValue]]?.selectLineWidth
          : state.loopOptions![extData.moduleId]?.settings[extData?.[loopKeyValue]]?.lineWidth
      })
    }

    // 点击回路回调
    // const handleClickPatternPolyline = async (polylineEvent: Record<string, any>) => {
    //   if (state.activePatternMarker) {
    //     if (state?.activePatternMarker?.getExtData?.()?.active)
    //       handleChangeEnlargeMarker({ target: state.activePatternMarker })
    //     state.activePatternMarker = undefined
    //     handleClearActiveMarkerEvent()
    //     emit('changePatterPolylineInfoView')
    //   }

    //   const extData = polylineEvent.target.getExtData()
    //   const res = await store.dispatch('loopMonitoringBox/GetDistributionIdByLoopId', {
    //     id: extData?.id
    //   })
    //   if (!res?.data) return
    //   if (!state.activePatternPolylineId[res?.data as string])
    //     state.activePatternPolylineId[res?.data as string] = []
    //   if (!state.activePatternPolylineId[res?.data as string]?.includes(extData?.id)) {
    //     handleChangePatternPolylineActiveStyle(true, polylineEvent.target)
    //     state.activePatternPolylineId[res?.data as string].push(extData?.id)
    //     return
    //   }
    //   handleChangePatternPolylineActiveStyle(false, polylineEvent.target)
    //   state.activePatternPolylineId[res?.data as string] = state.activePatternPolylineId[
    //     res?.data as string
    //   ]?.filter((item) => item !== extData?.id)
    // }

    // 更新回路选中事件
    const handleChangeActivePatternPolyline = (ids: string[], distributionId?: string) => {
      const usedDistributionId = distributionId || state.activePatternMarker?.getExtData?.()?.id
      const nextActiveIds = ids?.filter(
        (item) => !state.activePatternPolylineId[usedDistributionId]?.includes(item)
      )
      const nextCancelIds = state.activePatternPolylineId[usedDistributionId]?.filter(
        (item) => !ids?.includes(item)
      )
      // 把当前新增选中的 图形状态改为选中
      nextActiveIds?.forEach((item) => {
        if (state.patternPolyline![item])
          handleChangePatternPolylineActiveStyle(true, state.patternPolyline![item])
      })
      // 把当前取消选中的 图形状态改为未选中
      nextCancelIds?.forEach((item) => {
        if (state.patternPolyline![item])
          handleChangePatternPolylineActiveStyle(false, state.patternPolyline![item])
      })
      state.activePatternPolylineId[usedDistributionId] = ids
      return state.activePatternPolylineId[usedDistributionId]
    }

    //  绘制线
    // const handPolyline = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const activeLoopIds = JSON.stringify(state.activePatternPolylineId)
    //   const patternPolyline: AssetHomeMapStateType['patternPolyline'] = {}
    //   const { patternData } = props
    //   if (!patternData) return
    //   state.patternMarker = patternList?.reduce(
    //     (patternMarker: AssetHomeMapStateType['patternMarker'], item: Record<string, any>) => {
    //       const phase = item.phase ? item.phase : null
    //       // 当没有配置经纬度路经点时则不去生成图形
    //       if (!phase) return patternMarker
    //       if (phase.type === 'BaseStation' || phase.type === 'multiPolyline') {
    //         // 判断配置绘制层级
    //         // if(moduleId == null){
    //         //   moduleId = item.moduleId;
    //         // }

    //         const loopKeyValue = state.loopOptions![item.moduleId]?.key as keyof AssetHomeMarkerData

    //         // 找不到匹配的折线配置就return
    //         if (!loopKeyValue) return patternMarker
    //         const activeFlag = activeLoopIds?.includes(item.id)
    //         const polyline = new aMapRef.value.Polyline({
    //           // map: mapRef.value,
    //           path: phase.coordinates || [],
    //           title: item?.name,
    //           cursor: 'pointer',
    //           lineJoin: 'round',
    //           lineCap: 'round',
    //           strokeColor:
    //             state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineColor,
    //           strokeOpacity:
    //             state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineOpacity,
    //           strokeWeight: activeFlag
    //             ? state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.selectLineWidth
    //             : state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineWidth,
    //           zooms:
    //             state.loopOptions![item.moduleId].zooms?.length &&
    //             state.loopOptions![item.moduleId].zooms,
    //           extData: item
    //         })
    //         patternPolyline![item.id] = polyline
    //         // polyline.on('click', handleClickPatternPolyline)
    //         return patternMarker
    //       }

    //       return patternMarker
    //     },
    //     {}
    //   )

    //   state.patternPolyline = patternPolyline

    //   // 清理线并重新添加进图层展示
    //   const patternPolylineList = Values(state.patternPolyline)
    //   if (patternPolylineList?.length) {
    //     state.lineGroup = new aMapRef.value.OverlayGroup(patternPolylineList)
    //     mapRef.value.add(state.lineGroup)
    //   }
    // }

    //  绘制配电设施
    // const distributionDraw = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const zoom = mapRef.value.getZoom()
    //   const { patternData } = props
    //   if (!patternData) return
    //   const arr = []
    //   for (let i = 0; i < patternList.length; i++) {
    //     const item = patternList[i]
    //     const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
    //     const phase = item.phase

    //     if (item.moduleCode === 'BaseStation' && !state.distributionMarker?.[item.id]) {
    //       // 判断配置绘制层级
    //       if (
    //         zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
    //         zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
    //       )
    //         return

    //       state.distributionMarker[item.id] = item
    //       const markers = new aMapRef.value.LabelMarker({
    //         position: phase.coordinates,
    //         name: item?.name,
    //         icon: {
    //           type: 'image',
    //           image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
    //           size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize
    //         },
    //         extData: item ? { ...item, active: false } : { active: false },
    //         zooms:
    //           state.markerIconOptions![item.moduleId].zooms?.length &&
    //           state.markerIconOptions![item.moduleId].zooms
    //       })
    //       markers.on('rightclick', handleRightClickPatterMarker)
    //       markers.on('click', handleClickPatterMarker)
    //       arr.push(markers)
    //     }
    //   }

    //   distribution.value.add(arr)
    // }
    //  聚合点
    const count = ref(0)
    const gridSize = ref(60)
    const cluster = shallowRef()
    const markerCluster = (patternList: Record<string, any>[]) => {
      if (!patternList?.length) return
      count.value = patternList.length
      const arr = []
      for (let i = 0; i < patternList.length; i++) {
        const item = patternList[i]
        const phase = item.phase
        arr.push({
          lnglat: phase.coordinates,
          extData: item
        })
      }
      cluster.value = new aMapRef.value.MarkerCluster(mapRef.value, arr, {
        maxZoom: 13,
        gridSize: gridSize.value, // 设置网格像素大小
        renderClusterMarker: _renderClusterMarker, // 自定义聚合点样式
        renderMarker: _renderMarker // 自定义非聚合点样式
      })
    }
    //  聚合样式
    const _renderClusterMarker = (context: any) => {
      const factor = Math.pow(context.count / count.value, 1 / 18)
      const div = document.createElement('div')
      const Hue = 180 - factor * 180
      const bgColor = `hsla(${Hue},100%,40%,0.7)`
      const fontColor = `hsla(${Hue},100%,90%,1)`
      const borderColor = `hsla(${Hue},100%,40%,1)`
      const shadowColor = `hsla(${Hue},100%,90%,1)`
      div.style.backgroundColor = bgColor
      const size = Math.round(30 + Math.pow(context.count / count.value, 1 / 5) * 20)
      div.style.width = div.style.height = `${size}px`
      div.style.border = `solid 1px ${borderColor}`
      div.style.borderRadius = `${size / 2}px`
      div.style.boxShadow = `0 0 5px ${shadowColor}`
      div.innerHTML = context.count
      div.style.lineHeight = `${size}px`
      div.style.color = fontColor
      div.style.fontSize = '14px'
      div.style.textAlign = 'center'
      context.marker.setOffset(new aMapRef.value.Pixel(-size / 2, -size / 2))
      context.marker.setContent(div)
    }
    //  非聚合样式
    const _renderMarker = (context: any) => {
      const item = context.data[0].extData
      const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
      const zoom = mapRef.value.getZoom()
      let content = ''
      if (zoom >= 15) {
        content = `<div style="position: relative;left: -50%;">
        <style>
          .together{
            white-space: nowrap;
            margin-bottom: 5px;
            font-size: 13px;
            font-weight: 500;
            /* 设置描边宽度及颜色 */
            text-stroke: 2px #fff;
            /* 兼容Webkit(Chrome/Safari)内核浏览器的写法 */
            -webkit-text-stroke: 2px #fff;
          }
          /* 通过属性选择器结合伪元素before 实现文字外描边效果 */
          [data-content]::before {
            /* attr()是用来获取被选中元素的某属性值,并且在样式文件中使用 */
            content: attr(data-content);
            position: absolute;
            text-stroke: 0;
            /* 实现元素外描边的关键 */
            -webkit-text-stroke: 0;
            /* 文本颜色 */
            color: #F00;
          }
        </style>
        <div class="together" data-content=${item.name}>${item.name}</div>
        <img src="${
          state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl
        }" style="display: block;margin: auto;" width="28px" height="28px"/>
      </div>`
      } else {
        content = `<img src="${
          state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl
        }" width="28px" height="28px"/>`
      }
      const offset = new aMapRef.value.Pixel(-9, -9)
      context.marker.setContent(content)
      context.marker.setOffset(offset)
      context.marker.setExtData(item)
      context.marker.on('click', handleClickPatterMarker)
    }
    //  清空圆
    const drawCircleCrea = () => {
      mapRef.value.remove(drawCircleArray)
      mapRef.value.remove(drawLamppostMarker)
      drawCircleIds = []
      drawLamppostIds = []
      drawLamppostMarker = []
      drawCircleArray = []
    }
    //  画圆 114.17045&lat=30.58326
    let drawCircleIds = reactive<number[]>([])
    let drawCircleArray = reactive<any[]>([])
    const drawCircle = (radius: number, center: number[]) => {
      if (drawCircleIds.indexOf(center[0]) === -1) {
        drawCircleIds.push(center[0])
        const circle = new aMapRef.value.Circle({
          center: new aMapRef.value.LngLat(center[0], center[1]),
          radius,
          borderWeight: 2,
          strokeOpacity: 0,
          strokeDasharray: [10, 10],
          fillColor: '#ee2200',
          fillOpacity: 0.2
        })
        drawCircleArray.push(circle)
        mapRef.value.add(drawCircleArray)
      }
    }
    //  附近灯杆
    let drawLamppostIds = reactive<string[]>([])
    let drawLamppostMarker = reactive<any[]>([])
    const appendixLamppostDraw = (list: Record<string, any>[]) => {
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (drawLamppostIds.indexOf(item.id) === -1) {
          drawLamppostIds.push(item.id)
          const markers = new aMapRef.value.Marker({
            position: item.phase.coordinates,
            content: `<div style="position: relative;left: -50%;">
              <div style="white-space: nowrap;color:red;font-weight: 500;font-size: 13px;">${item.code}</div>
            <img src="${lampost}" style="display: block;margin: auto;" width="28px" height="28px"/>
            </div>`,
            extData: item
          })
          drawLamppostMarker.push(markers)
          markers.on('click', appendixLamppostInfo)
        }
      }
      mapRef.value.add(drawLamppostMarker)
    }
    //  附近灯杆详情
    const appendixLamppostInfo = async (markerEvent: Record<string, any>) => {
      const extData = markerEvent.target.getExtData()
      const { data } = await store.dispatch('base/GetLampPostById', { id: extData.id })
      if (!data) return
      const mapClientRect = mapDomRef.value.getBoundingClientRect()
      const patternMarkerOffset = mapRef.value.lngLatToContainer(markerEvent.target!.getPosition())
      state.activePatternMarker = markerEvent.target
      const datainfo = {
        name: data.code,
        assetId: extData.id,
        moduleCode: 'lightPole',
        moduleName: '灯杆',
        infoList: [
          { type: 'text', key: '灯杆经度', value: data.lon },
          { type: 'text', key: '灯杆纬度', value: data.lat },
          { type: 'text', key: '详细地址', value: data.address }
        ]
      }
      emit(
        'changePatterMarkerInfoView',
        patternMarkerOffset.x + mapClientRect.left,
        patternMarkerOffset.y + mapClientRect.top + 18,
        'BaseStation',
        datainfo,
        []
      )
      // 给map注册拖动事件 让popover 随着拖动移动
      mapRef.value.on('mapmove', handleReplacePatterDomOffset)
      mapRef.value.on('resize', handleReplacePatterDomOffset)
      mapRef.value.on('moveend', handleJudgeActivePatterMarkerInMap)
    }

    //  绘制灯杆
    // const lamppostDraw = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const zoom = mapRef.value.getZoom()
    //   const { patternData } = props
    //   if (!patternData) return
    //   const arr = []
    //   for (let i = 0; i < patternList.length; i++) {
    //     const item = patternList[i]
    //     const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
    //     const phase = item.phase

    //     if (item.moduleCode === 'LampPost' && !state.lamppostMarker?.[item.id]) {
    //       // 判断配置绘制层级
    //       if (
    //         zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
    //         zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
    //       )
    //         return

    //       state.lamppostMarker[item.id] = item
    //       const markers = new aMapRef.value.LabelMarker({
    //         position: phase.coordinates,
    //         name: item?.name,
    //         // 判断是灯的话层级 要覆盖在灯杆上
    //         zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
    //         icon: {
    //           type: 'image',
    //           image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
    //           size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize,
    //           offset:
    //             item?.moduleCode === 'LampBase' && state.lampPostModuleId
    //               ? [
    //                 0,
    //                 state.markerIconOptions![state.lampPostModuleId]?.icons[item?.[keyValue]]
    //                   .offset[1] * 0.6
    //               ]
    //               : undefined
    //         },
    //         text: {
    //           content: item?.name,
    //           direction: 'top',
    //           zooms: [18, 20],
    //           style: {
    //             fillColor: styles.successColor,
    //             strokeColor: styles.whiteColor
    //           }
    //         },
    //         extData: item ? { ...item, active: false } : { active: false },
    //         zooms:
    //           state.markerIconOptions![item.moduleId].zooms?.length &&
    //           state.markerIconOptions![item.moduleId].zooms
    //       })
    //       arr.push(markers)
    //       // markers.on('click', handleClickPatterMarker)
    //     }
    //   }
    //   lamppost.value.add(arr)
    // }

    //  绘制灯
    // const lampDraw = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const zoom = mapRef.value.getZoom()
    //   const { patternData } = props
    //   if (!patternData) return
    //   const arr = []
    //   for (let i = 0; i < patternList.length; i++) {
    //     const item = patternList[i]
    //     const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
    //     const phase = item.phase

    //     if (item.moduleCode === 'LampBase' && !state.lampMarker?.[item.id]) {
    //       // 判断配置绘制层级

    //       if (
    //         zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
    //         zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
    //       )
    //         return

    //       state.lampMarker[item.id] = item
    //       const markers = new aMapRef.value.LabelMarker({
    //         position: phase.coordinates,
    //         name: item?.name,
    //         // 判断是灯的话层级 要覆盖在灯杆上
    //         zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
    //         icon: {
    //           type: 'image',
    //           image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
    //           size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize,
    //           offset:
    //             item?.moduleCode === 'LampBase' && state.lampPostModuleId
    //               ? [
    //                 0,
    //                 state.markerIconOptions![state.lampPostModuleId]?.icons[item?.[keyValue]]
    //                   .offset[1] * 0.6
    //               ]
    //               : undefined
    //         },
    //         extData: item ? { ...item, active: false } : { active: false },
    //         zooms:
    //           state.markerIconOptions![item.moduleId].zooms?.length &&
    //           state.markerIconOptions![item.moduleId].zooms
    //       })
    //       arr.push(markers)
    //       markers.on('click', handleClickPatterMarker)
    //     }
    //   }
    //   lamp.value.add(arr)
    // }

    //  绘制名称灯
    // const lamptitleDraw = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const zoom = mapRef.value.getZoom()
    //   const { patternData } = props
    //   if (!patternData) return
    //   const arr = []
    //   for (let i = 0; i < patternList.length; i++) {
    //     const item = patternList[i]
    //     const phase = item.phase

    //     if (item.moduleCode === 'LampBase' && !state.lampTitleMarker?.[item.id]) {
    //       // 判断配置绘制层级
    //       if (
    //         zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
    //         zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
    //       )
    //         return

    //       state.lampTitleMarker[item.id] = item
    //       const markers = new aMapRef.value.LabelMarker({
    //         position: phase.coordinates,
    //         name: item?.name,
    //         // 判断是灯的话层级 要覆盖在灯杆上
    //         zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
    //         text: {
    //           content: item?.name,
    //           direction: 'top',
    //           zooms: [25, 20],
    //           style: {
    //             fillColor: styles.successColor,
    //             strokeColor: styles.whiteColor
    //           },
    //           offset: [0, -20]
    //         },
    //         extData: item ? { ...item, active: false } : { active: false },
    //         zooms:
    //           state.markerIconOptions![item.moduleId].zooms?.length &&
    //           state.markerIconOptions![item.moduleId].zooms
    //       })
    //       arr.push(markers)
    //     }
    //   }
    //   lamptitle.value.add(arr)
    // }

    // 根据传入数组渲染对应的图案
    // const handleDrawPattern = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const { activeOptionsBar } = props

    //   //  当灯跟杆同时存在时，为ture
    //   const activeOptionsBarShow =
    //     activeOptionsBar!.indexOf('LampPost') > -1 && activeOptionsBar!.indexOf('LampBase') > -1

    //   // 将选中的所有回路数据转字符串 在渲染时如果有匹配的 则高亮 否则则正常展示
    //   const activeLoopIds = JSON.stringify(state.activePatternPolylineId)

    //   // 先把已有的点或线更新数据
    //   patternList?.forEach((item: Record<string, any>) => {
    //     if (item.moduleCode === 'DistributionLoop' && state.patternPolyline![item?.id]) {
    //       const phase = item.phase ? item.phase : null
    //       state.patternPolyline![item.id].setExtData(item)
    //       state.patternPolyline![item.id].setPath(phase.coordinates || [])
    //       return
    //     }
    //     if (state.patternMarker?.[item?.moduleId]?.[item?.id]) {
    //       const phase = item.phase ? item.phase : null
    //       state.patternMarker![item.moduleId][item.id].setPosition(phase.coordinates)
    //       state.patternMarker![item.moduleId][item.id].setName(item?.name)
    //       // LampPost
    //       if (activeOptionsBarShow && item.moduleCode === 'LampBase') {
    //         state.patternMarker![item.moduleId][item.id].setText({
    //           content: ''
    //         })
    //       } else {
    //         state.patternMarker![item.moduleId][item.id].setText({
    //           content: item?.name
    //         })
    //       }
    //     }
    //   })

    //   // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
    //   const activeMarkerExtData = state.activePatternMarker?.getExtData?.()

    //   const patternPolyline: AssetHomeMapStateType['patternPolyline'] = {}

    //   // 生成新的点和线
    //   state.patternMarker = patternList?.reduce(
    //     (patternMarker: AssetHomeMapStateType['patternMarker'], item: Record<string, any>) => {
    //       let content = null
    //       if (activeOptionsBarShow && item.moduleCode === 'LampBase') {
    //         content = ''
    //       } else {
    //         content = item?.name
    //       }
    //       // 将已有的数据过滤并返回 无需再次生成
    //       if (
    //         item.moduleCode === 'DistributionLoop' &&
    //         item.id &&
    //         state.patternPolyline![item.id]
    //       ) {
    //         patternPolyline![item.id] = state.patternPolyline![item.id]
    //         return patternMarker
    //       }
    //       if (state.patternMarker?.[item?.moduleId]?.[item?.id]) {
    //         if (patternMarker![item.moduleId]) {
    //           patternMarker![item.moduleId][item.id] =
    //             state.patternMarker?.[item.moduleId]?.[item.id]
    //         } else {
    //           patternMarker![item.moduleId] = {
    //             [item.id]: state.patternMarker?.[item.moduleId]?.[item.id]
    //           }
    //         }
    //         return patternMarker
    //       }

    //       const phase = item.phase ? item.phase : null
    //       // 当没有配置经纬度路经点时则不去生成图形
    //       if (!phase) return patternMarker
    //       // 如果当前为回路则生成折线
    //       if (phase.type === 'polyline' || phase.type === 'multiPolyline') {
    //         const loopKeyValue = state.loopOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
    //         // 找不到匹配的折线配置就return
    //         if (!loopKeyValue) return patternMarker
    //         const activeFlag = activeLoopIds?.includes(item.id)
    //         const polyline = new aMapRef.value.Polyline({
    //           // map: mapRef.value,
    //           path: phase.coordinates || [],
    //           title: item?.name,
    //           cursor: 'pointer',
    //           lineJoin: 'round',
    //           lineCap: 'round',
    //           strokeColor:
    //             state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineColor,
    //           strokeOpacity:
    //             state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineOpacity,
    //           strokeWeight: activeFlag
    //             ? state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.selectLineWidth
    //             : state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineWidth,
    //           zooms:
    //             state.loopOptions![item.moduleId].zooms?.length &&
    //             state.loopOptions![item.moduleId].zooms,
    //           extData: item
    //         })
    //         patternPolyline![item.id] = polyline
    //         polyline.on('click', handleClickPatternPolyline)
    //         return patternMarker
    //       }
    //       const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
    //       if (phase.type !== 'point' || !keyValue || !state.markerIconOptions![item.moduleId])
    //         return patternMarker
    //       const marker = new aMapRef.value.LabelMarker({
    //         position: phase.coordinates,
    //         name: item?.name,
    //         // 判断是灯的话层级 要覆盖在灯杆上
    //         zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
    //         icon: {
    //           type: 'image',
    //           image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
    //           size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize,
    //           offset:
    //             // state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.offset
    //             item?.moduleCode === 'LampBase' && state.lampPostModuleId
    //               ? [
    //                 0,
    //                 state.markerIconOptions![state.lampPostModuleId]?.icons[item?.[keyValue]]
    //                   .offset[1] * 0.6
    //               ]
    //               : undefined
    //         },
    //         text: {
    //           content,
    //           direction: 'top',
    //           zooms: [18, 20],
    //           style: {
    //             fillColor: styles.successColor,
    //             strokeColor: styles.whiteColor
    //           }
    //         },
    //         extData: item ? { ...item, active: false } : { active: false },
    //         zooms:
    //           state.markerIconOptions![item.moduleId].zooms?.length &&
    //           state.markerIconOptions![item.moduleId].zooms
    //       })
    //       if (patternMarker![item.moduleId]) {
    //         patternMarker![item.moduleId][item.id] = marker
    //       } else {
    //         patternMarker![item.moduleId] = { [item.id]: marker }
    //       }

    //       if (item?.moduleCode === 'Distribution') {
    //         marker.on('rightclick', handleRightClickPatterMarker)
    //       }
    //       marker.on('click', handleClickPatterMarker)
    //       if (
    //         activeMarkerExtData?.id === item?.id &&
    //         activeMarkerExtData?.moduleId === item?.moduleId
    //       )
    //         handleChangeEnlargeMarker({ target: marker })

    //       return patternMarker
    //     },
    //     {}
    //   )
    //   state.patternPolyline = patternPolyline

    //   // // 清理线并重新添加进图层展示
    //   // const patternPolylineList = Values(state.patternPolyline)
    //   // if (patternPolylineList?.length) {
    //   //   state.polylineLayer!.clear()
    //   //   state.polylineLayer!.add(Values(state.patternPolyline))
    //   //   state.polylineLayer!.show()
    //   // }

    //   // 清理点并重新添加进图层展示
    //   // state.markerLayer?.clear?.()
    //   // state.markerLayer?.add?.(
    //   //   Values(state.patternMarker)
    //   //     ?.map((item: Record<string, any>) => Values(item))
    //   //     .flat()
    //   // )
    //   // state.markerLayer?.show?.()
    // }

    // 根据父元素传入的moduleid查询当前地图可视区域内的所有配电设施路灯及灯具marker
    const handleSearchMapMarkerByModuleId = async () => {
      const { activeModules } = props

      // const bounds = mapRef.value.getBounds()
      // 西北（左上）
      // const northWest = bounds.getNorthWest()
      // 东南（右下）
      // const southEast = bounds.getSouthEast()
      // const zoom = mapRef.value.getZoom()

      if (activeModules?.length) {
        //   setTimeout(() => {
        //     const { activeOptionsBar } = props
        //     if (activeOptionsBar!.indexOf('BaseStation') > -1) {
        //       distribution.value && distribution.value.show()
        //     } else {
        //       distribution.value && distribution.value.hide()
        //     }
        //   }, 50)
        // const res = await store.dispatch('assetHome/GetAssetHomeBaseDataByModuleId', {
        //   moduleIds: activeModules?.join(','),
        //   leftLatitude: northWest.lat,
        //   leftLongitude: northWest.lng,
        //   rightLatitude: southEast.lat,
        //   rightLongitude: southEast.lng,
        //   level: zoom
        // })
        // lamppostDraw(res?.data)
        //   lampDraw(res?.data)
        //   lamptitleDraw(res?.data)
        //   handleDrawPattern(res?.data)
      }

      // if (zoom >= 14) {
      //   cluster.value.setData([])
      // } else {
      //   markerClusterAjax()
      // }
    }

    // 根据传入的坐标点数据对比当前选中的是否一致 不一致则切换一致（场景用于多点重合一个位置）
    const handleChangeActivePatternMarker = (record: Record<string, any>) => {
      if (state.patternMarker![record?.moduleId]) {
        if (state.patternMarker![record?.moduleId][record?.id]) {
          if (state.activePatternMarker) {
            handleChangeEnlargeMarker({ target: state.activePatternMarker })
          }
          state.activePatternMarker = state.patternMarker![record?.moduleId][record?.id]
          // 如果当前替换的还是原来的则恢复其放大状态
          if (!state.activePatternMarker!.getExtData()?.active)
            handleChangeEnlargeMarker({ target: state.activePatternMarker })
        }
      }
    }

    // 清空当前绘制点并重新绘制设备点
    const handleDrawEquipmentPoint = (patternList: Record<string, any>[]) => {
      if (patternList?.length) {
        const firstDataParse = patternList[0]?.phase
        if (!firstDataParse?.coordinates?.length) return
        const mapZoom = mapRef.value.getZoom()
        if (
          mapZoom >
            props.patternData?.[patternList[0]?.moduleId]?.modelConfigDataVO?.base?.minScale! &&
          mapZoom <
            props.patternData?.[patternList[0]?.moduleId]?.modelConfigDataVO?.base?.maxScale!
        ) {
          mapRef.value.setCenter(firstDataParse.coordinates, false, 0)
        } else {
          mapRef.value.setZoomAndCenter(
            props.patternData?.[patternList[0]?.moduleId]?.modelConfigDataVO?.base?.minScale ??
              mapRef.value.getZoom(),
            firstDataParse.coordinates,
            false,
            0
          )
        }
      }
    }

    // 清空当前查询的设备点 并重新绘制当前可视区域的所有坐标点
    const handleClearEquipmentPoint = () => {
      // lineBool.value = true
      // 先移除所有的坐标点和线
      // handleClearDrawPattern()
      handleSearchMapMarkerByModuleId()
    }

    //  地区查询
    const district = shallowRef()
    const polygon = ref(null)
    const loadSearchRef = ref<LoadingInstance>()
    const handleSearchDistribution = (position: string, positionName: string) => {
      loadSearchRef.value = ElLoading.service({
        target: `#${props.id}`,
        text: '地图渲染中，请稍后'
      })
      if (!district.value) {
        district.value = new aMapRef.value.DistrictSearch({
          subdistrict: 0,
          extensions: 'all',
          level: 'district'
        })
      }
      district.value.setLevel(position)
      district.value.search(positionName, (status: any, result: any) => {
        if (polygon.value) {
          mapRef.value.remove(polygon.value)
          polygon.value = null
        }
        const bounds = result.districtList[0].boundaries
        if (bounds) {
          for (let i = 0; i < bounds.length; i += 1) {
            bounds[i] = [bounds[i]]
          }
          polygon.value = new aMapRef.value.Polygon({
            strokeWeight: 1,
            path: bounds,
            fillOpacity: 0.4,
            fillColor: '#80d8ff',
            strokeColor: '#0091ea'
          })
          mapRef.value.add(polygon.value)
          mapRef.value.setFitView(polygon.value)

          loadSearchRef.value!.close()
        }
      })

      setTimeout(() => {
        loadSearchRef.value!.close()
      }, 3000)
    }

    const markerClusterAjax = async (obj?: any) => {
      const { activeModules } = props
      // const bounds = mapRef.value.getBounds()
      // 西北（左上）
      // const northWest = bounds.getNorthWest()
      // 东南（右下）
      // const southEast = bounds.getSouthEast()
      // const zoom = mapRef.value.getZoom()
      const res = await store.dispatch('assetHome/GetAssetHomeBaseDataByModuleIdStationGisApi', {
        moduleIds: activeModules?.join(','),
        leftLatitude: '44.716113',
        leftLongitude: '87.173316',
        rightLatitude: '13.28354',
        rightLongitude: '141.445776',
        level: 5,
        specialCode: 'basestation_home',
        ...obj
      })
      if (res.data.length === 0) ElMessage({ type: 'warning', message: '未匹配到数据' })
      if (obj && res.data.length > 0) {
        const { coordinates } = res.data[0].phase
        mapRef.value.setZoomAndCenter(14, coordinates, false, 1500)
      }
      cluster.value?.setData()
      markerCluster(res?.data)
    }
    //  卫星地图展示切换
    const satelliteChangingOver = (value: boolean) => {
      if (!value) {
        mapRef.value.removeLayer(satellite.value)
      } else {
        mapRef.value.addLayer(satellite.value)
      }
    }

    // 初始化map事件
    async function initAMap() {
      // mapRef.value.addLayer(aMapRef.value.createDefaultLayer())
      await props.initCallback()
      loadRef.value!.close()

      satellite.value = new aMapRef.value.TileLayer.Satellite()
      // mapRef.value.addLayer(satellite.value)

      mapRef.value.on('zoomend', () => {
        // handleSearchMapMarkerByModuleId()
        props.getMapZoom?.()
      })

      //  灯杆图层
      lamppost.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      mapRef.value.add(lamppost.value)
      //  灯图层
      lamp.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      // mapRef.value.add(lamp.value)
      //  灯名称图层
      lamptitle.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      // mapRef.value.add(lamptitle.value)
      //  配电设施图层
      distribution.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      // mapRef.value.add(distribution.value)

      markerClusterAjax()
      // handPolyline(res?.data)
      // distributionDraw(res?.data)
    }

    onMounted(() => {
      loadRef.value = ElLoading.service({
        target: `#${props.id}`,
        text: '加载中'
      })
    })

    onBeforeUnmount(() => {
      mapRef.value.clearMap()
      mapRef.value.destroy()
    })

    expose({
      map: mapRef,
      aMap: aMapRef,
      amapIcon: amapIconRef,
      restCenter: handleRestMapCenter,
      setMapInfo: handleSetMapInfo,
      toggleWorkAreaPolygonVisible: handleChangePolygonVisible,
      showAreaPolygonByAreaId: handleShowAreaPolygonByAreaId,
      searchMapMarker: handleSearchMapMarkerByModuleId,
      clearActiveMarkerEvent: handleClearActiveMarkerEvent,
      generateMarkerIcon: handleGenerateMarkerIcon,
      getPatterMarkerInfo: handleGetPatterMarkerInfoBy,
      changeActivePatternMarker: handleChangeActivePatternMarker,
      changeActivePatternPolyline: handleChangeActivePatternPolyline,
      drawEquipmentPoint: handleDrawEquipmentPoint,
      clearEquipmentPoint: handleClearEquipmentPoint,
      handleSearchDistribution,
      markerClusterAjax,
      appendixLamppostDraw,
      drawCircle,
      drawCircleCrea,
      satelliteChangingOver
    })
    return () => (
      <>
        <section id={props.id} ref={mapDomRef}></section>
      </>
    )
  }
})
